package com.appspot.thinkhea.view;

import java.util.Vector;

import com.appspot.thinkhea.R;
import com.appspot.thinkhea.model.Picture;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class IconSimpleAdapter extends BaseAdapter {
	private LayoutInflater mInflater;
	private Vector<Picture> v;
	private Context context;
	private Vector<Boolean> selected;

	public IconSimpleAdapter(Context context, Vector<Picture> v) {
		this.v = v;
		this.context = context;
		mInflater = LayoutInflater.from(context);
		selected = new Vector<Boolean>();
		for (int a = 0; a < v.size(); a++) {
			selected.add(false);
		}
	}

	@Override
	public int getCount() {
		return v.size();
	}

	@Override
	public Object getItem(int position) {
		return v.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.list_item_picture, null);
			holder = new ViewHolder();
			holder.name = (TextView) convertView.findViewById(R.id.Name);
			holder.detail = (TextView) convertView.findViewById(R.id.Detail);
			holder.icon = (ImageView) convertView.findViewById(R.id.Bitmap);
			convertView.setTag(holder);
		} else {
			// reuse convertView
			holder = (ViewHolder) convertView.getTag();
		}

		Bitmap img = v.get(position).getImage();
		if (img != null) {
			img = Bitmap.createScaledBitmap(img, 48, 65, false);
		} else {
			img = BitmapFactory.decodeResource(this.context.getResources(),
					R.drawable.unknown);
		}
		Bitmap mIcon = img;
		String mName = v.get(position).getName();
		String mDetail = v.get(position).getDetail();
		holder.name.setText(mName);
		holder.detail.setText(mDetail);
		holder.icon.setImageBitmap(mIcon);

		if (selected.get(position) == true) {
			convertView.setBackgroundColor(R.color.color_yellow);
		} else {
			convertView.setBackgroundColor(0);
		}

		return convertView;
	}

	private class ViewHolder {
		TextView name;
		TextView detail;
		ImageView icon;
	}

	public void setSelected(int position) {
		for (int c = 0; c < selected.size(); c++) {
			if (c == position) {
				selected.set(c, true);
			} else {
				selected.set(c, false);
			}
		}
		this.notifyDataSetChanged();
		this.notifyDataSetInvalidated();
	}

	public int getSelected() {
		for (int c = 0; c < selected.size(); c++) {
			if (selected.get(c) == true) {
				return c;
			}
		}
		return -1;
	}
}